/**
 * Write a program that does the following. Execute a loop five times: create a message
 * queue, print the queue identifier, delete the message queue. Then execute the next loop
 * five times: create a message queue with a key of IPC_PRIVATE, and place a message on
 * the queue. After the program terminates, look at the message queues using ipcs(1).
 * Explain what is happening with the queue identifiers.
 * 
 * 程序输出：
[ 0 ] msgid = 491520
[ 0 ] removed.
[ 1 ] msgid = 524288
[ 1 ] removed.
[ 2 ] msgid = 557056
[ 2 ] removed.
[ 3 ] msgid = 589824
[ 3 ] removed.
[ 4 ] msgid = 622592
[ 4 ] removed.
-----------------------------
[ 0 ] msgid = 655360
[ 1 ] msgid = 688129
[ 2 ] msgid = 720898
[ 3 ] msgid = 753667
[ 4 ] msgid = 786436
 * ipcs相关输出:
------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x00000000 655360     mxw        600        1            1           
0x00000000 688129     mxw        600        1            1           
0x00000000 720898     mxw        600        1            1           
0x00000000 753667     mxw        600        1            1           
0x00000000 786436     mxw        600        1            1
 **/
#include "apue.h"

#include <sys/msg.h>

int main()
{
  int msgid, i;
  struct buf {
    long type;
    char msg[1];
  } buf;

  buf.type = 1;
  buf.msg[0] = 'a';

  for (i = 0; i < 5; i++) {
    // 创建队列
    msgid = msgget(IPC_PRIVATE, IPC_CREAT | S_IWUSR | S_IRUSR);
    if (msgid < 0) {
      printf("[ %d ] msgget failed.\n", i);
    } else {
      printf("[ %d ] msgid = %d\n", i, msgid);
    }
    // printf("[ %d ] removing msgqueue...\n", i);
    // 删除队列
    if (msgctl(msgid, IPC_RMID, NULL) != 0) {
      printf("[ %d ] remove failed.\n", i);
    } else {
      printf("[ %d ] removed.\n", i);
    }
  }

  printf("-----------------------------\n");

  for (i = 0; i < 5; i++) {
    // 创建消息队列
    msgid = msgget(IPC_PRIVATE, IPC_CREAT | S_IWUSR | S_IRUSR);
    if (msgid < 0) {
      printf("[ %d ] msgget failed.\n", i);
    } else {
      printf("[ %d ] msgid = %d\n", i, msgid);
    }
    // 放入消息
    if (msgsnd(msgid, &buf, 1, 0) != 0) {
      printf("[ %d ] msgsnd failed.\n", i);
    }
  }
  return 0;
}